<template>
	<view class="takePic">
		<view class="form">
			<uni-forms ref="form" :rules="{}">
				<view v-for="(item,index) in entity.imglist" :key="index">
					<view style="display: flex;justify-content: space-between;" v-if="item.Mtype==='audio'">
						<eliseAudio audioId="audio1" :url="item.Murl" audioColor="#68d7bb" :durationS="item.duration"
							ref="eliseAudio" v-if="item.Mtype==='audio'" style="margin-bottom: 10px;"></eliseAudio>

						<uni-icons type="trash" v-if="item.Mtype==='audio'" @click="imgDel(item.Murl)" class="color"
							size="20" color="red"></uni-icons>
					</view>
				</view>
				<uni-forms-item name="">
					<uni-grid :column="3" :showBorder="false">
						<view v-for="(item,index) in entity.imglist" :key="index">
							<uni-grid-item style="position: relative;padding: 5rpx;box-sizing: border-box;"
								v-if="item.Mtype==='image'||item.Mtype==='video'">
								<image :src="item.Murl" style="width: 100%;height: 100%;"
									@click="lookimg(entity.imglist,'',index)" v-if="item.Mtype==='image'"></image>
								<view
									style="width: 100%;height: 100%;background: #000;position: relative;display: flex;justify-content: center;align-items: center;"
									v-if="item.Mtype==='video'" @click="lookimg(entity.imglist,'',index)">
									<uni-icons type="videocam-filled" size="30" color="#fff"></uni-icons>
								</view>

								<uni-icons type="trash-filled" @click="imgDel(item.Murl)" class="color" size="20"
									color="#fff"
									style="position: absolute; right: 5%;top: 5%;z-index: 9; background-color:#ef0a0a; border-radius: 5px;">
								</uni-icons>
							</uni-grid-item>
						</view>

						<uni-grid-item>
							<button
								style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;"
								@click="$refs.popup.open()">
								<uni-icons type="camera-filled" size="30"></uni-icons>
							</button>
						</uni-grid-item>
					</uni-grid>
				</uni-forms-item>
				<!-- 模板 -->
				<uni-forms-item v-for="item in PropData" :key="item.ControlKey" :label="item.ControlName"
					:name="item.ControlKey">
					<text v-if="item.ControlName == '楼层' && isText==true "
						style="color:red;font-size:22rpx">*仅可输入"符号和字符"</text>
					<view v-if="item.ControlName == '楼层'"
						style="display: flex;border:1px solid #E5E5E5;border-radius: 10rpx;padding: 12rpx;">
						<!-- 	<uni-easyinput placeholder="请输入" type="number" @input="propInput($event,item)"
							v-model="entity[item.ControlKey]" suffixIcon="z层"></uni-easyinput> -->
						<input placeholder-style="font-size:23rpx;padding-left:8rpx" placeholder="请输入(如负一层请输入 -1 )"
							type="text" @input="propInput($event,item)" v-model="entity[item.ControlKey]" suffixIcon="层"
							@focus="propInputFocus" @blur="propInputBlur"></input>
					</view>
					<view v-if="item.ControlType == 'select'">
						<uni-data-select @change="propItemChange($event,item)" v-model="entity[item.ControlKey]"
							:localdata="item.CVdata">
						</uni-data-select>
						<uni-easyinput @confirm="customize(item)" @blur="customize(item)" placeholder="输入后点击键盘确认进行添加"
							v-if="entity[item.ControlKey]=='自定义'" v-model="item.customize">
						</uni-easyinput>
					</view>
					<uni-easyinput placeholder="请输入" v-if="item.ControlType == 'input'&&item.ControlName!='楼层'"
						@input="propInput($event,item)" v-model="entity[item.ControlKey]"></uni-easyinput>
					<view class="formCheck" v-if="item.ControlType == 'checkBox'">
						<view class="input" @click="openCheck(item)">
							<view class="value" v-if="entity[item.ControlKey]">{{entity[item.ControlKey]}}</view>
							<view class="noValue" v-else>请选择</view>
						</view>
						<view>
							<uni-icons @click="openCheck(item)" v-if="!entity[item.ControlKey]" type="bottom" size="14"
								color="#989898"></uni-icons>
							<uni-icons @click="clearCheckBoxSelect(item)" v-else type="clear" size="24"
								color="#c0c4cc"></uni-icons>
						</view>
						<CheckBoxSelect :ref="'CheckBoxSelect'+item.ControlKey"
							@confirm="CheckBoxSelectConfirm($event,item)" @add="addItem" />
					</view>
				</uni-forms-item>
				<uni-forms-item name="" style="position: relative;">
					<uni-easyinput type="textarea" autoHeight v-model="entity.Content" placeholder="描述内容"
						:maxlength="-1">
					</uni-easyinput>
					<!-- <uni-icons type="mic-filled" size="20" style="position: absolute;bottom: 10px;right: 10px;"
						@click="audioOpen()"></uni-icons> -->
				</uni-forms-item>
			</uni-forms>
			<button type="warn" @click="submit">保存</button>
		</view>
		<view class="preForm" v-show="preEntity.Content">
			<view class="preTitle">
				<text>上次提交</text>
				<!-- <text class="more" @click="toHistoricalRecord">更多</text> -->
			</view>
			<view class="preRemark">
				{{preEntity.Content}}
			</view>
			<view class="prePicBox">
				<view v-for="(item,index) in preEntity.imglist" :key="index" :class="index%3 == 1?'pic margin':'pic'">
					<image style="width: 100%;height: 100%" :src="item.Murl" mode="aspectFill"></image>
				</view>
			</view>
		</view>
		<!-- <uni-popup ref="audio" type="bottom" @close="audioClose" style="position: relative;" :is-mask-click="false"
			@maskClick="audioClose">

			<nb-voice-record @startRecord="start" @endRecord="end" @cancelRecord="cancel" btnDefaultText="录音"
				:popupFixBottom="250" btnHoverBgcolor="red" btnHoverFontcolor='#fff'
				:btnStyle="{width:'70px',height:'70px',background: 'red',color:'#fff',borderRadius: '50%',fontSize:'16px'}"
				style="float: left;margin-left: calc(50% - 35px);margin-bottom: 100rpx;">
			</nb-voice-record>
		</uni-popup> -->
		<ImageView ref="ImageView" @setEdit="setEditObj"></ImageView>
		<videoView ref="videoView"></videoView>
		<uni-popup ref="popup" type="bottom">
			<view style="padding: 10rpx;">
				<button @click="upclick('拍照')">拍照</button>
				<button style="margin-top: 10rpx;" @click="upclickVideo('拍视频')">拍视频</button>
				<button style="margin-top: 10rpx;" @click="upclickImage('相册选取')">相册选取</button>
			</view>
		</uni-popup>
		<!-- </uni-transition> -->
	</view>
</template>

<script>
	import ImageView from '@/components/ImageView.vue'
	import videoView from '@/components/videoView.vue'
	import eliseAudio from '@/components/elise-audio/elise-audio.vue'
	import tabBar from '@/components/tabBar.vue'
	import CheckBoxSelect from '@/components/checkBoxSelect.vue'
	export default {
		components: {
			ImageView,
			eliseAudio,
			videoView,
			tabBar,
			CheckBoxSelect
		},
		onNavigationBarButtonTap(e) {
			console.log(e)
			uni.navigateTo({
				url: '/pages/user/user'
			})
			return true;
		},
		computed: {
			loginStates() {
				return uni.getStorageSync('loginStates')
			}
		},
		onHide() {
			console.log('离开');
		},
		data() {
			return {
				isText: false,
				style: {
					width: '100%',
					height: '100%',
				},
				preEntity: {},
				play: true,
				voicePath: "",
				radio: 0,
				radiolist: [

					{
						text: '在线模式',
						value: 1,
					},
					{
						text: '离线模式',
						value: 0,
					},

				],
				imglist: [],
				arr: ['camera'],
				ImgUrl: '',
				range: [{
					text: '1',
					value: '1',
					disabled: false
				}],
				ischose: false, //监听缓存提交
				entity: {
					Content: "",
					value: "",
					imglist: []
				},
				PropData: [],
				btnObject: {
					bg: '#fff',
					paddingR: '20',
					paddingL: '20',
					left: [],
					right: [{
						Name: '保存',
						type: 'warn',
						size: 'mini'
					}]
				},
				editObj: '',
				newType: ""
			}
		},
		onShow() {

			this.PropData = uni.getStorageSync('propData') || []
			if (this.PropData.length == 0) {
				this.$http('Base_ProjectWork/Base_Project/GetTakeNotesTypeData').then(res => {
					console.log(res);
					if (res.Success) {
						this.PropData = res.Data
						uni.setStorageSync('propData', res.Data)
					}
				})
			}
			// 本地缓存中读取是否有编辑数据
			if (uni.getStorageSync('editFile')) {
				let entity = JSON.parse(uni.getStorageSync('editFile'))
				let arr = [...entity.PropData, ...this.PropData]
				let newArr = []
				entity.PropData.forEach((item, index) => {
					let arr = [...this.PropData[index].CVdata, ...item.CVdata]
					let objn = {}
					let arrn = []
					arr.forEach(val => {
						if (!objn[val.value]) {
							objn[val.value] = 1
							arrn.push(val)
						} else {
							objn[val.value] += 1
						}
					})
					item.CVdata = arrn
					newArr.push(item)

				})
				this.entity = entity
				this.PropData = this.entity.PropData
			}
			console.log('onShow TakePic');
			// 是否有编辑图片数据
			if (uni.getStorageSync('localImgList')) {
				this.entity.imglist = JSON.parse(uni.getStorageSync('localImgList'))
				// this.$refs.ImageView.changeImgList(this.entity.imglist)
				uni.removeStorageSync('localImgList')
			}
		},
		methods: {
			addItem(list) {
				uni.setStorageSync('propData', this.PropData)
			},
			clearCheckBoxSelect(item) {
				item.DefaultValue = ''
				this.$set(this.entity, item.ControlKey, '')
			},
			CheckBoxSelectConfirm(e, item) {
				item.DefaultValue = e.join(',')
				this.$set(this.entity, item.ControlKey, item.DefaultValue)
			},
			openCheck(item) {
				this.$refs['CheckBoxSelect' + item.ControlKey][0].open(item.CVdata, item.DefaultValue)
			},
			// 存储画图数据
			setEditObj() {
				console.log('存储画图数据');
				uni.setStorageSync('localImgList', this.editObj)
			},
			tabBarSelect(e) {
				if (e == '保存') {
					this.submit()
				}
			},
			// 自定义
			customize(item) {
				if (item.CVdata.findIndex((im) => im.value == item.customize) !== -1)
					return this.$message.error("当前添加项已存在于列表中");
				item.CVdata.unshift({
					value: item.customize,
					text: item.customize,
				});
				this.$set(this.entity, item.ControlKey, item.customize);
				item.DefaultValue = item.customize;
				item.customize = "";
			},
			// 动态列表选择
			propItemChange(e, item) {
				if (e !== "自定义") {
					item.DefaultValue = e;
				}
			},
			// 动态列表填写
			propInput(e, item) {
				item.DefaultValue = e.detail.value;
				const inputRule = /[^\d_-]/g //只能输入数字和部分特殊字符
				this.$nextTick(function() { //针对楼层
					this.entity[item.ControlKey] = e.detail.value.replace(inputRule, '');
				})
			},
			// 楼层输入获取焦点提示
			propInputFocus() {
				console.log('获取焦点了')
				this.isText = true
			},
			// 楼层输入失去焦点
			propInputBlur() {
				this.isText = false
			},
			// 历史提交
			toHistoricalRecord() {
				uni.navigateTo({
					url: './HistoricalRecord'
				})
			},
			// 开始拍照
			startTakePic() {
				this.upclick()
				uni.showTabBar()
				this.show = false
			},
			audioClose() {
				uni.showTabBar()
				this.$refs.audio.close()
			},
			audioOpen() {
				uni.hideTabBar()
				this.$refs.audio.open()
			},
			start() {
				console.log('开始录音')
				// 开始录音
			},
			end(event) {
				this.audioClose()
				console.log(event)
				var audio1 = uni.createInnerAudioContext();
				audio1.src = event.tempFilePath
				var duration = 0
				setTimeout(() => {
					duration = audio1.duration.toFixed(2)
					var strFileName = event.tempFilePath.substring(event.tempFilePath.lastIndexOf("/") + 1)

					this.entity.imglist.push({
						Mtype: 'audio',
						name: strFileName,
						audioplay: true,
						duration: audio1.duration.toFixed(2),
						Id: new Date().getTime(),
						Murl: event.tempFilePath
					})
					console.log(this.entity.imglist)
					console.log(event)
				}, 100)

				// 结束录音并处理得到的录音文件
				// event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段
			},
			cancel() {
				console.log('取消录音')
				// 用户取消录音
			},

			imgDel(url) { //删除图片
				console.log('删除图片', url, this.entity);
				let idx = this.entity.imglist.findIndex(item => item.Murl == url)
				if (idx === -1) return
				// #ifdef H5
				this.entity.imglist.splice(idx, 1)
				// #endif
				// #ifdef APP
				uni.removeSavedFile({ //删除本地文件 
					filePath: this.entity.imglist[idx].Murl,
					success: (res) => {
						console.log(res);
					},
					fail: (err) => {
						console.log(err);
					},
					complete: (resa) => {
						this.entity.imglist.splice(idx, 1)
					}
				});
				// #endif
			},

			lookvideo(path) {
				this.$refs.videoView.open(path)
			},
			lookimg(arr, content, index) { //查看图片
				console.log('EditImgPage页面查看图片', arr, content, index)
				let obj = {
					imageList: arr,
					current: index,
					type: 'local',
					Content: this.entity.Content
				}
				this.$refs.ImageView.open(obj)
				this.editObj = JSON.stringify(this.entity.imglist)
			},
			upclick(type) { //上传图片到本地获取到本地地址
				this.newType = type
				console.log('拍照了', this.newType)

				this.$refs.popup.close()
				this.ischose = true

				console.log(uni.chooseMedia)

				uni.chooseImage({
					sizeType: ['original', 'compressed'],
					sourceType: ['camera'],
					success: (res) => {
						console.log(res)
						// 临时路径注释 H5页面测试可放开后注释下面的
						// #ifdef H5
						var strFileName = res.tempFilePaths[0].substring(res.tempFilePaths[0].lastIndexOf(
							"/") + 1)
						var obj = {
							Mtype: "image",
							Murl: res.tempFilePaths[0],
							name: strFileName
						}
						this.entity.imglist.push(obj)
						// #endif
						//保存本地永久路径 APP
						// #ifdef APP
						// 压缩图片
						uni.compressImage({
							src: res.tempFilePaths[0],
							quality: 30,
							success: result => {
								// 保存到本地
								uni.saveFile({
									tempFilePath: result.tempFilePath,
									success: (val) => {
										console.log(val)
										var strFileName = val.savedFilePath.substring(
											val.savedFilePath
											.lastIndexOf("/") + 1)
										var obj = {
											Id: new Date().getTime(),
											Mtype: "image",
											Murl: val.savedFilePath,
											name: strFileName
										}

										this.entity.imglist.push(obj)
										console.log(this.entity.imglist);
									}
								});
							}
						})
						// #endif
					}
				})
			},
			upclickVideo(type) {
				// 初始化相册选取再次调用相机
				this.newType = type
				console.log('拍视频了', this.newType)
				this.$refs.popup.close()
				this.ischose = true
				uni.chooseVideo({
					sourceType: ['camera'],
					success: (res) => {
						console.log(res)
						//临时路径注释 H5页面测试可放开后注释下面的
						// #ifdef H5
						var strFileName = res.tempFilePath.substring(res.tempFilePath
							.lastIndexOf("/") + 1)
						var obj = {
							Mtype: "video",
							Murl: res.tempFilePath,
							name: strFileName
						}
						this.entity.imglist.push(obj)
						// #endif
						//保存永久本地路径
						// #ifdef APP
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: (val) => {
								console.log(val)
								var strFileName = val.savedFilePath.substring(val.savedFilePath
									.lastIndexOf("/") + 1)
								var obj = {
									Id: new Date().getTime(),
									Mtype: "video",
									Murl: val.savedFilePath,
									name: strFileName
								}
								this.entity.imglist.push(obj)

								console.log('save success');
							}
						});
						// #endif
					}
				});
			},
			// 开始相册选择
			upclickImage(type) {
				// 赋值  用于判断只有相册选取条件下才不会再次弹拍照
				this.newType = type
				console.log('相册选取了', this.newType)
				uni.showTabBar()
				this.$refs.popup.close()
				this.ischose = true
				console.log(uni.chooseMedia)
				uni.chooseImage({
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: (res) => {
						console.log('上传后的图片是', res)
						// 临时路径注释 H5页面测试可放开后注释下面的
						// #ifdef H5
						var strFileName = res.tempFilePaths[0].substring(res.tempFilePaths[0].lastIndexOf(
							"/") + 1)
						var obj = {
							Mtype: "image",
							Murl: res.tempFilePaths[0],
							name: strFileName,
							FileSize: res.tempFiles[0].size
						}
						this.entity.imglist.push(obj)
						// #endif
						//保存本地永久路径 APP
						// #ifdef APP
						// 压缩图片
						uni.compressImage({
							src: res.tempFilePaths[0],
							quality: 30,
							success: result => {
								// 保存到本地
								uni.saveFile({
									tempFilePath: result.tempFilePath,
									success: (val) => {
										console.log('保存到本地结果', val)
										console.log(val)
										var strFileName = val.savedFilePath.substring(
											val.savedFilePath
											.lastIndexOf("/") + 1)
										var obj = {
											Id: new Date().getTime(),
											Mtype: "image",
											Murl: val.savedFilePath,
											name: strFileName,
											FileSize: res.tempFiles[0].size
										}

										this.entity.imglist.push(obj)
										console.log('获取最终push到数组的图片', this.entity
											.imglist);
									}
								});
							}
						})
						// #endif
					}
				})

				this.show = false
			},

			async submit() {
				var that = this
				// setTimeout(() => {
				// 	this.upclick()
				// }, 1000)
				// return
				if (this.entity.imglist.length <= 0) return uni.showToast({
					title: '请至少保留一张照片',
					icon: "none"
				});
				if (!this.entity.Content) {
					uni.showToast({
						title: '请输入描述内容',
						icon: "none"
					});
					return
				}
				let fromData = uni.getStorageSync('fromdata')
				let row = uni.getStorageSync('editFile')
				let arr = JSON.parse(fromData)
				let idx = arr.findIndex(item => item.Id == this.entity.Id)
				if (idx !== -1) {
					this.PropData.forEach(item => {
						item.DefaultValue = this.entity[item.ControlKey]
					})
					this.entity.PropData = this.PropData
					arr[idx] = this.entity
					uni.setStorageSync('fromdata', JSON.stringify(arr))
					uni.removeStorageSync('editFile')
					uni.switchTab({
						url: '/pages/Tool/Tool'
					})
					uni.showToast({
						title: '修改成功',
						duration: 500
					})
					return
				}

			}

		}
	}
</script>

<style lang="scss" scoped>
	.image {
		height: 200px;
		width: 90vw;
		margin: 0 auto;
		display: block;
	}

	.margin {
		margin: 0 2%;
	}

	.fixedBtn {
		position: fixed;
		bottom: 70px;
		right: 20rpx;
		/* #ifdef APP */
		bottom: 20rpx;
		/* #endif */
	}

	.takePic {
		background-color: #f8f8f8;
		height: 100%;
		overflow: scroll;

		.preForm {

			background: #fff;
			padding: 10px;
			border-top: 1px solid #ccc;

			.preTitle {
				font-weight: bold;
				font-size: 20px;
				margin-bottom: 5px;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.more {
					font-weight: normal;
					font-size: 16px
				}
			}

			.prePicBox {
				display: flex;
				flex-wrap: wrap;
				margin: 20rpx 0;

				.pic {
					height: 210rpx;
					box-sizing: border-box;
					border: 1px solid #ccc;
					width: 32%;
					margin-bottom: 10rpx;

				}
			}
		}

		.formCheck {
			width: 100%;
			flex: 1;
			border: 1px solid #e5e5e5;
			box-sizing: border-box;
			border-radius: 4px;
			padding: 0 5px;
			padding-left: 10px;
			position: relative;
			display: flex;
			align-items: center;
			border-bottom: solid 1px #e5e5e5;
			-webkit-user-select: none;
			user-select: none;
			flex-direction: row;
			max-width: 100%;
			height: 35px;
			color: #6a6a6a;
			font-size: 12px;

			.input {
				flex: 1;
				max-width: 100%;

				.value {
					width: 460rpx;
					font-size: 14px;
					color: rgb(58, 58, 58);
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
			}
		}

		.example {
			z-index: 10;
			background-image: url('../../static/start.jpg');
			position: fixed;
			background-size: cover;
			background-repeat: no-repeat;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;

			.icon {
				position: fixed;
				right: 10px;
				top: 54px;
			}

			button {
				position: fixed;
				color: #d1100a;
				font-weight: bold;
				top: 50%;
				left: 0;
				right: 0;
				bottom: 0;
				margin: auto;
				width: 245rpx;
				height: 100rpx;
				line-height: 100rpx;
				border-radius: 50px;
				// border: 1px solid rgba(0, 0, 0, .2);
				box-shadow: 0px 4px 0px 0 rgba(0, 0, 0, .2);
			}

			.backBtn {
				top: 70%;
			}
		}

		.form {
			// margin-top: 20px;
			background-color: #fff;
			padding: 20px;
		}
	}

	.content {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		/* #ifdef H5 */
		height: calc(100vh - var(--window-bottom) - var(--window-top));
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		transition: opacity 0.3s;
		background: #999;
		opacity: 0;

		&.active {
			opacity: 1;
		}

		.logo {
			position: relative;
			margin-top: -400upx;
			width: 200upx;
			height: 200upx;
			// z-index: -1;
			opacity: 0;
			transition: opacity 0.3s;

			&.active {
				opacity: 1;
			}
		}
	}

	.tabbar-box-wrap {
		position: absolute;
		width: 100%;
		padding: 50upx;
		box-sizing: border-box;
		bottom: 0;
		left: 0;

		.tabbar-box {
			position: relative;
			display: flex;
			width: 100%;
			background: #fff;
			border-radius: 20upx;
			padding: 15upx 20upx;
			box-sizing: border-box;
			z-index: 2;
			box-shadow: 0px 2px 5px 2px rgba(0, 0, 0, 0.1);

			&:after {
				content: '';
				position: absolute;
				bottom: -16upx;
				left: 0;
				right: 0;
				margin: auto;
				width: 50upx;
				height: 50upx;
				transform: rotate(45deg);
				background: #fff;
				z-index: 1;
				box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.1);
				border-radius: 2px;
			}

			&:before {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: #ffffff;
				border-radius: 20upx;
				z-index: 2;
			}

			.tabbar-box-item {
				// position: relative;
				width: 100%;
				z-index: 3;
				margin: 10upx;
				color: $uni-color-subtitle;
				text-align: center;
				font-size: $uni-font-size-base;

				.box-image {
					width: 100%;
					height: $uni-img-size-lg;
				}
			}
		}
	}
</style>